﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace LdCms.Web.Controllers.API.Community.V1
{
    using LdCms.Common.Extension;
    using LdCms.Common.Utility;
    using LdCms.Common.Net;
    using LdCms.IBLL.Community;
    using LdCms.EF.DbModels;
    using LdCms.Common.Web;
    using LdCms.Web.Services;
    using LdCms.Common.Enum;
    using LdCms.BLL.Community;

    [ApiVersion("1.0")]
    [ControllerName("community/theme/reply")]
    public class CommunityThemeReplyController : BaseApiController
    {
        private readonly IBaseApiManager BaseApiManager;
        private readonly IHttpContextAccessor Accessor;
        private readonly IColumnService ColumnService;
        private readonly IColumnPermissionService ColumnPermissionService;
        private readonly IThemeService ThemeService;
        private readonly IThemeReplyService ThemeReplyService;
        private readonly IBLL.Sys.IConfigService SysConfigService;
        public CommunityThemeReplyController(IBaseApiManager BaseApiManager, IHttpContextAccessor Accessor, IColumnService ColumnService, IColumnPermissionService ColumnPermissionService, IThemeService ThemeService, IThemeReplyService ThemeReplyService, IBLL.Sys.IConfigService SysConfigService) : base(BaseApiManager)
        {
            this.BaseApiManager = BaseApiManager;
            this.Accessor = Accessor;
            this.ColumnService = ColumnService;
            this.ColumnPermissionService = ColumnPermissionService;
            this.ThemeService = ThemeService;
            this.ThemeReplyService = ThemeReplyService;
            this.SysConfigService = SysConfigService;
        }
        /// <summary>
        /// 回复主题
        /// </summary>
        /// <param name="uuid"></param>
        /// <param name="fromValue"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("save")]
        public IActionResult SaveThemeReply(string uuid, [FromBody]JObject fromValue)
        {
            long logId = 0;
            try
            {
                logId = BaseApiManager.SaveLogs(uuid, fromValue);
                int systemId = InterfaceAccount.SystemID;
                string companyId = InterfaceAccount.CompanyID;
                string memberId = GetJObjectValue(fromValue, "memberid");
                string nickName = GetJObjectValue(fromValue, "nickname");
                string themeId = GetJObjectValue(fromValue, "themeid");
                string parentReplyId = GetJObjectValue(fromValue, "parentid");
                string imgSrc = GetJObjectValue(fromValue, "image_src");
                string imgArray = GetJObjectValue(fromValue, "image_src_array");
                string content = GetJObjectValue(fromValue, "content");

                if (string.IsNullOrWhiteSpace(themeId))
                    return Error(logId, "主题编号不能为空！");
                if (string.IsNullOrWhiteSpace(content))
                    return Error(logId, "内容不能为空！");

                var entityConfig = SysConfigService.GetConfig(SystemID, companyId);
                if (entityConfig != null)
                {
                    string Shielding = entityConfig.Shielding;
                    if (!string.IsNullOrWhiteSpace(Shielding))
                    {
                        string[] keyword = Shielding.Split("|");
                        if (!IsKeyword(keyword, content))
                            return Error(logId, "内容有非法虑字！");
                    }
                }
                var entityTheme = ThemeService.GetTheme(SystemID, companyId, themeId);
                if (entityTheme == null)
                    return Error(logId, "主题ID无效！");
                string columnId = entityTheme.ColumnID;
                bool themeLock = entityTheme.IsLock.ToBool();
                if (themeLock)
                    return Error(logId, "主题已锁定不能再回复！");

                var entityColumn = ColumnService.GetColumn(SystemID, companyId, columnId);
                if (entityColumn == null)
                    return Error(logId, "column id invalid！");
                bool columnState = entityColumn.State.ToBool();
                bool columnLock = entityColumn.IsLock.ToBool();
                bool columnReply = entityColumn.IsReply.ToBool();

                if (!columnState)
                    return Error(logId, "专栏已停用！");
                if (columnLock)
                    return Error(logId, "专栏已锁定，不能回复新贴！");
                if (columnReply)
                {
                    if (string.IsNullOrWhiteSpace(memberId))
                        return Error(logId, "会员帐号不能为空！");
                    int typeId = (int)ParamEnum.ColumnPermission.回帖权限;
                    var memberColumnPermission = ColumnPermissionService.VerifyColumnPermission(SystemID, companyId, columnId, memberId, typeId);
                    if (!memberColumnPermission)
                        return Error(logId, "您没本专栏回贴权限！");
                }
                var entity = new Ld_Community_ThemeReply()
                {
                    SystemID = SystemID,
                    CompanyID = companyId,
                    ThemeID = themeId,
                    ImgSrc = imgSrc,
                    ImgArray = Utility.ContentDecode(imgArray),
                    ReplyContent = content,
                    ParentReplyID = string.IsNullOrWhiteSpace(parentReplyId) ? "0" : parentReplyId,
                    MemberID = string.IsNullOrWhiteSpace(memberId) ? "1".PadRight(16, '0') : memberId,
                    NickName = string.IsNullOrWhiteSpace(nickName) ? "匿名" : nickName,
                    IpAddress=Net.Ip,
                    State =  true
                };
                var result = ThemeReplyService.SaveThemeReply(entity);
                if (result)
                    return Success(logId, "ok");
                else
                    return Error(logId, "fail");
            }
            catch (Exception ex)
            {
                return Error(logId, ex.Message);
            }
        }


        #region 私有方法
        private bool IsKeyword(string[] keyword, string content)
        {
            foreach (var item in keyword)
            {
                if (content.ToLower().Contains(item.ToLower()))
                    return false;
            }
            return true;
        }
        private bool IsSaveParams(JObject formValue)
        {
            try
            {
                if (formValue == null)
                    throw new Exception("params not empty！");
                if (formValue.Property("column_id") == null)
                    throw new Exception("lack theme id params！");
                if (formValue.Property("content") == null)
                    throw new Exception("lack content params！");
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion

    }
}